<template>
  <div class="dictionary-container" style="padding: 20px; max-width: 1000px; margin: 0 auto;">
    <!-- 操作按钮 -->
    <el-button type="primary" @click="handleAdd" style="margin-bottom: 20px;">新增字典项</el-button>

    <!-- 数据表格 -->
    <el-table :data="keywords" border style="width: 100%" :default-sort="{ prop: 'id', order: 'ascending' }">
      <el-table-column prop="id" label="ID" sortable width="80" />
      <el-table-column prop="type" label="类型" width="200">
        <template #default="scope">
          <span>{{ typeLabels[scope.row.type] || scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="value" label="值" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗表单 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%;" :disabled="!!editId">
            <el-option
              v-for="(label, key) in typeLabels"
              :key="key"
              :label="label"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="form.value" placeholder="请输入关键字内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { saveKeyApi, deleteKeyApi, getKeyApi, updateKeyApi } from '../../api/System'

// 类型映射（便于显示）
const typeLabels = {
  'company_type_id': '公司类型',
  'job_type_id': '招聘类型',
  'educational_background_id': '最低学历',
  'status_id': '状态',
  'candidate_id': '招聘对象',
  'home_title': '首页标题',
  'home_text': '首页文案'
}

// 响应式数据
const keywords = ref([])
const dialogVisible = ref(false)
const editId = ref(null)
const form = ref({
  type: '',
  value: ''
})
const formRef = ref(null)

// 表单验证规则
const rules = {
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入值', trigger: 'blur' }]
}

// 计算属性：对话框标题
const dialogTitle = computed(() => editId.value ? '编辑字典项' : '新增字典项')

// 获取所有字典数据
const fetchKeywords = async () => {
  try {
    const res = await getKeyApi()
    keywords.value = res.data || []
  } catch (error) {
    ElMessage.error('获取数据失败：' + (error.message || '未知错误'))
  }
}

// 新增
const handleAdd = () => {
  form.value = { type: '', value: '' }
  editId.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  form.value = { ...row }
  editId.value = row.id
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除 "${row.value}" 吗？`, '警告', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用删除接口
      await deleteKeyApi(row.id)
      ElMessage.success('删除成功')
      fetchKeywords() // 刷新列表
    } catch (error) {
      ElMessage.error('删除失败：' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单（新增/更新）
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (editId.value) {
        // 更新
        form.value.id = editId.value
        await updateKeyApi(form.value)
        ElMessage.success('更新成功')
      } else {
        // 新增
        await saveKeyApi(form.value)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchKeywords() // 刷新列表
    } catch (error) {
      ElMessage.error((error.response?.data?.message || error.message) || '操作失败')
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchKeywords()
})
</script>

<style scoped>
.dictionary-container {
  font-family: Arial, sans-serif;
}
.dialog-footer {
  text-align: right;
}
</style>